package com.software.views;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Random;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;


public class ClassManager {
    private static final List<Group> groupList = new ArrayList<>();   // 小组列表
    private static final List<Student> studentList = new ArrayList<>(); // 学生列表
    private static List<CourseClass> classList = new ArrayList<>();
    private static CourseClass currentClass = null;

    // 获取当前班级
    public static CourseClass getCurrentClass() {
        return currentClass;
    }

    // 设置当前班级
    public static void setCurrentClass(CourseClass classInstance) {
        currentClass = classInstance;
    }

    // 显示新增小组窗口
    public static void showAddGroupFrame() {
        JFrame addGroupFrame = new JFrame("新增小组");
        addGroupFrame.setSize(400, 200);
        addGroupFrame.setLocationRelativeTo(null);
        addGroupFrame.setLayout(new BorderLayout());

        JLabel title = new JLabel("新增小组", JLabel.CENTER);
        title.setFont(new Font("宋体", Font.BOLD, 18));
        addGroupFrame.add(title, BorderLayout.NORTH);

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout());
        JLabel nameLabel = new JLabel("小组名称：");
        JTextField nameField = new JTextField(15);
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);
        addGroupFrame.add(inputPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        JButton addButton = new JButton("新增");
        JButton backButton = new JButton("返回");

        buttonPanel.add(addButton);
        buttonPanel.add(backButton);

        addGroupFrame.add(buttonPanel, BorderLayout.SOUTH);
        addGroupFrame.setVisible(true);

        addButton.addActionListener(e -> {
            String groupName = nameField.getText();
            if (!groupName.isEmpty()) {
                Group newGroup = new Group(groupName, currentClass.getId());
                groupList.add(newGroup);
                JOptionPane.showMessageDialog(addGroupFrame, "小组新增成功！");
            } else {
                JOptionPane.showMessageDialog(addGroupFrame, "小组名称不能为空！");
            }
        });

        // 修改返回按钮监听器，确保正确显示当前班级
        backButton.addActionListener(e -> {
            addGroupFrame.dispose();
            MenuFrame.updateCurrentClassLabel(currentClass != null ? currentClass.getName() : "请选择班级");
            MenuFrame.showMenuFrame();
        });
    }



    // 显示小组列表窗口
    public static void showGroupListFrame() {
        JFrame groupListFrame = new JFrame("小组列表");
        groupListFrame.setSize(600, 400); // 窗口大小
        groupListFrame.setLocationRelativeTo(null);
        groupListFrame.setLayout(new BorderLayout());

        // 创建顶部面板，包含搜索框和按钮
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("查询");
        JButton deleteButton = new JButton("删除");
        JButton backButton = new JButton("返回");

        topPanel.add(searchField);
        topPanel.add(searchButton);
        topPanel.add(backButton);
        topPanel.add(deleteButton);

        groupListFrame.add(topPanel, BorderLayout.NORTH);

        // 表格数据和列名
        String[] columnNames = {"小组ID", "小组名称"};
        String[][] data = getGroupData(groupList);
        JTable table = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        groupListFrame.add(scrollPane, BorderLayout.CENTER);

        // 查询按钮逻辑
        searchButton.addActionListener(e -> {
            String query = searchField.getText().trim();
            List<Group> filteredGroups = new ArrayList<>();
            if (query.isEmpty()) {
                filteredGroups.addAll(groupList);
            } else {
                for (Group group : groupList) {
                    if (group.getName().contains(query)) {
                        filteredGroups.add(group);
                    }
                }
            }
            String[][] newData = getGroupData(filteredGroups);
            table.setModel(new javax.swing.table.DefaultTableModel(newData, columnNames));
        });

        // 删除按钮逻辑
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int confirm = JOptionPane.showConfirmDialog(groupListFrame, "确认删除该小组？", "删除小组", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    Group groupToRemove = groupList.get(selectedRow);
                    groupList.remove(groupToRemove);
                    studentList.removeIf(student -> student.getGroup().getId().equals(groupToRemove.getId()));
                    JOptionPane.showMessageDialog(groupListFrame, "小组及其相关的学生已删除");
                    showGroupListFrame();  // 重新显示小组列表
                }
            } else {
                JOptionPane.showMessageDialog(groupListFrame, "请先选择一个小组");
            }
        });

        // 返回按钮逻辑
        backButton.addActionListener(e -> {
            groupListFrame.dispose();
            MenuFrame.showMenuFrame();
        });

        groupListFrame.setVisible(true);
    }

    private static String[][] getGroupData(List<Group> groups) {
        String[][] data = new String[groups.size()][2];
        for (int i = 0; i < groups.size(); i++) {
            Group group = groups.get(i);
            data[i][0] = group.getId();
            data[i][1] = group.getName();
        }
        return data;
    }

    // 显示新增学生窗口
    public static void showAddStudentFrame() {
        JFrame addStudentFrame = new JFrame("新增学生");
        addStudentFrame.setSize(400, 300);
        addStudentFrame.setLocationRelativeTo(null);
        addStudentFrame.setLayout(new BorderLayout());

        JLabel title = new JLabel("新增学生", JLabel.CENTER);
        title.setFont(new Font("宋体", Font.BOLD, 18));
        addStudentFrame.add(title, BorderLayout.NORTH);

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(3, 2, 10, 10));

        JLabel groupLabel = new JLabel("选择小组：");
        // 使用只显示名称的 Group 对象
        JComboBox<Group> groupComboBox = new JComboBox<>(groupList.toArray(new Group[0]));
        JLabel nameLabel = new JLabel("姓名：");
        JTextField nameField = new JTextField(15);
        JLabel idLabel = new JLabel("学号：");
        JTextField idField = new JTextField(15);  // 学号输入框

        inputPanel.add(groupLabel);
        inputPanel.add(groupComboBox);
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);
        inputPanel.add(idLabel);
        inputPanel.add(idField);

        addStudentFrame.add(inputPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        JButton addButton = new JButton("新增");
        JButton backButton = new JButton("返回");

        buttonPanel.add(addButton);
        buttonPanel.add(backButton);

        addStudentFrame.add(buttonPanel, BorderLayout.SOUTH);

        addStudentFrame.setVisible(true);

        // 按钮点击事件：新增学生
        addButton.addActionListener(e -> {
            String studentName = nameField.getText();
            String studentId = idField.getText();  // 获取管理员输入的学号
            Group selectedGroup = (Group) groupComboBox.getSelectedItem();
            if (!studentName.isEmpty() && !studentId.isEmpty() && selectedGroup != null) {
                // 使用管理员输入的学号来创建学生对象
                Student newStudent = new Student(studentId, studentName, selectedGroup);
                studentList.add(newStudent);
                JOptionPane.showMessageDialog(addStudentFrame, "学生新增成功！");
            } else {
                JOptionPane.showMessageDialog(addStudentFrame, "信息不完整！");
            }
        });

        // 返回按钮：关闭当前窗口并返回菜单
        backButton.addActionListener(e -> {
            addStudentFrame.dispose();
            MenuFrame.updateCurrentClassLabel(currentClass != null ? currentClass.getName() : "请选择班级");
            MenuFrame.showMenuFrame();
        });

    }

    // 显示学生列表窗口
    public static void showStudentListFrame() {
        JFrame studentListFrame = new JFrame("学生列表");
        studentListFrame.setSize(600, 400);
        studentListFrame.setLocationRelativeTo(null);
        studentListFrame.setLayout(new BorderLayout());

        JLabel titleLabel = new JLabel("学生列表", JLabel.CENTER);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 18));
        studentListFrame.add(titleLabel, BorderLayout.NORTH);

        if (currentClass == null) {
            JOptionPane.showMessageDialog(studentListFrame, "请先设置班级");
            return;
        }

        // 创建顶部面板，包含搜索框和按钮
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JTextField idSearchField = new JTextField(10);
        JTextField nameSearchField = new JTextField(10);
        JButton searchButton = new JButton("查询");
        JButton deleteButton = new JButton("删除");
        JButton backButton = new JButton("返回");

        topPanel.add(new JLabel("学号："));
        topPanel.add(idSearchField);
        topPanel.add(new JLabel("姓名："));
        topPanel.add(nameSearchField);
        topPanel.add(searchButton);
        topPanel.add(backButton);
        topPanel.add(deleteButton);

        studentListFrame.add(topPanel, BorderLayout.NORTH);

        // 获取当前班级的学生列表
        List<Student> currentClassStudents = studentList.stream()
                .filter(student -> student.getGroup().getClassId().equals(currentClass.getId()))
                .collect(Collectors.toList());

        String[] columnNames = {"学号", "姓名", "小组"};
        String[][] data = getStudentData(currentClassStudents);
        JTable table = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        studentListFrame.add(scrollPane, BorderLayout.CENTER);

        // 查询按钮逻辑
        searchButton.addActionListener(e -> {
            String idQuery = idSearchField.getText().trim();
            String nameQuery = nameSearchField.getText().trim();

            // 创建一个新的过滤后的学生列表
            List<Student> filteredStudents = new ArrayList<>();

            if (idQuery.isEmpty() && nameQuery.isEmpty()) {
                // 如果两个输入框都为空，显示所有学生
                filteredStudents.addAll(currentClassStudents);
            } else {
                for (Student student : currentClassStudents) {
                    boolean matchesId = idQuery.isEmpty() || student.getId().contains(idQuery);
                    boolean matchesName = nameQuery.isEmpty() || student.getName().contains(nameQuery);

                    // 如果学号条件存在，必须满足学号过滤；如果姓名条件存在，必须满足姓名过滤
                    if ((!idQuery.isEmpty() && matchesId) && nameQuery.isEmpty()) {
                        filteredStudents.add(student);
                    } else if ((!nameQuery.isEmpty() && matchesName) && idQuery.isEmpty()) {
                        filteredStudents.add(student);
                    } else if (!idQuery.isEmpty() && !nameQuery.isEmpty() && matchesId && matchesName) {
                        filteredStudents.add(student);
                    }
                }
            }

            // 更新表格数据
            String[][] newData = getStudentData(filteredStudents);
            table.setModel(new javax.swing.table.DefaultTableModel(newData, columnNames));
        });

        // 删除按钮逻辑
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int confirm = JOptionPane.showConfirmDialog(studentListFrame, "确认删除该学生？", "删除学生", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    Student studentToRemove = currentClassStudents.get(selectedRow);
                    studentList.remove(studentToRemove);
                    JOptionPane.showMessageDialog(studentListFrame, "学生已删除");
                    showStudentListFrame();  // 刷新学生列表
                }
            } else {
                JOptionPane.showMessageDialog(studentListFrame, "请先选择一个学生");
            }
        });

        // 返回按钮逻辑
        backButton.addActionListener(e -> {
            studentListFrame.dispose();
            // 更新主菜单的班级标签
            MenuFrame.updateCurrentClassLabel(currentClass != null ? currentClass.getName() : "请选择班级");
            MenuFrame.showMenuFrame();
        });

        studentListFrame.setVisible(true);
    }

    private static String[][] getStudentData(List<Student> students) {
        String[][] data = new String[students.size()][3];
        for (int i = 0; i < students.size(); i++) {
            Student student = students.get(i);
            data[i][0] = student.getId();
            data[i][1] = student.getName();
            data[i][2] = student.getGroup().getName();
        }
        return data;
    }



    // 登录页面
    public static void showLoginFrame() {
        JFrame loginFrame = new JFrame("登录");
        loginFrame.setSize(350, 200);  // 调整窗口大小
        loginFrame.setLocationRelativeTo(null);
        loginFrame.setLayout(new BorderLayout());

        JLabel titleLabel = new JLabel("用户登录", JLabel.CENTER);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 20));  // 增大字体
        loginFrame.add(titleLabel, BorderLayout.NORTH);

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(2, 2, 5, 5));  // 调整间距

        JLabel userLabel = new JLabel("用户名：", JLabel.RIGHT);
        userLabel.setFont(new Font("宋体", Font.PLAIN, 16));  // 调整字体大小
        JTextField userField = new JTextField(10);  // 缩小输入框
        inputPanel.add(userLabel);
        inputPanel.add(userField);

        JLabel passLabel = new JLabel("密码：", JLabel.RIGHT);
        passLabel.setFont(new Font("宋体", Font.PLAIN, 16));
        JPasswordField passField = new JPasswordField(10);  // 缩小输入框
        inputPanel.add(passLabel);
        inputPanel.add(passField);

        loginFrame.add(inputPanel, BorderLayout.CENTER);

        JButton loginButton = new JButton("登录");
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);
        loginFrame.add(buttonPanel, BorderLayout.SOUTH);

        loginFrame.setVisible(true);
    }

    // 新增班级窗口
    public static void showAddClassFrame() {
        JFrame addClassFrame = new JFrame("新增班级");
        addClassFrame.setSize(400, 200);
        addClassFrame.setLocationRelativeTo(null);
        addClassFrame.setLayout(new BorderLayout());

        JLabel title = new JLabel("新增班级", JLabel.CENTER);
        title.setFont(new Font("宋体", Font.BOLD, 18));
        addClassFrame.add(title, BorderLayout.NORTH);

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout());
        JLabel nameLabel = new JLabel("班级名称：");
        JTextField nameField = new JTextField(15);
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);
        addClassFrame.add(inputPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        JButton addButton = new JButton("新增");
        JButton backButton = new JButton("返回");

        buttonPanel.add(addButton);
        buttonPanel.add(backButton);

        // 状态标签
        JLabel statusLabel = new JLabel("", JLabel.CENTER);
        statusLabel.setForeground(Color.RED);

        // 创建一个额外的面板来容纳按钮和状态标签
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS));
        bottomPanel.add(buttonPanel);
        bottomPanel.add(Box.createVerticalStrut(10));  // 增加间距
        bottomPanel.add(statusLabel);

        addClassFrame.add(bottomPanel, BorderLayout.SOUTH);

        // 设置框架可见
        addClassFrame.setVisible(true);

        addButton.addActionListener(e -> {
            String className = nameField.getText();
            if (!className.isEmpty()) {
                boolean classExists = classList.stream().anyMatch(cls -> cls.getName().equals(className));
                if (classExists) {
                    statusLabel.setText("班级已存在");
                    statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
                } else {
                    CourseClass newClass = new CourseClass(className);
                    classList.add(newClass);
                    statusLabel.setText("新增成功");
                    statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
                }
            } else {
                statusLabel.setText("班级名称不能为空");
                statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
            }
        });


        backButton.addActionListener(e -> {
            addClassFrame.dispose();
            MenuFrame.showMenuFrame();
        });
    }

    // 班级列表
    public static void showClassListFrame() {
        JFrame classListFrame = new JFrame("班级列表");
        classListFrame.setSize(500, 400);
        classListFrame.setLocationRelativeTo(null);
        classListFrame.setLayout(new BorderLayout());

        // 标题
        JLabel titleLabel = new JLabel("班级列表", JLabel.CENTER);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 18));
        classListFrame.add(titleLabel, BorderLayout.NORTH);

        // 表格数据和列名
        String[] columnNames = {"班级ID", "班级名称"};
        String[][] data = new String[classList.size()][2];
        for (int i = 0; i < classList.size(); i++) {
            CourseClass cls = classList.get(i);
            data[i][0] = cls.getId(); // 获取班级ID
            data[i][1] = cls.getName(); // 获取班级名称
        }
        JTable table = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        classListFrame.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(1, 5, 10, 0));  // 调整为网格布局，5个按钮并排显示，增加间距

        // 创建五个按钮
        JButton queryButton = new JButton("查询");
        JButton setClassButton = new JButton("设置班级");
        JButton exportButton = new JButton("导出成绩");
        JButton deleteButton = new JButton("删除");
        JButton backButton = new JButton("返回");

        // 查询按钮事件
        queryButton.addActionListener(e -> {
            // 更新表格数据
            String[][] newData = new String[classList.size()][2];
            for (int i = 0; i < classList.size(); i++) {
                CourseClass cls = classList.get(i);
                newData[i][0] = cls.getId();
                newData[i][1] = cls.getName();
            }
            table.setModel(new javax.swing.table.DefaultTableModel(newData, columnNames));
        });

        // 设置班级按钮事件
        setClassButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                currentClass = classList.get(selectedRow);
                classListFrame.dispose();
                MenuFrame.updateCurrentClassLabel(currentClass.getName());
            } else {
                JOptionPane.showMessageDialog(classListFrame, "请先选择一个班级");
            }
        });

        // 导出成绩按钮事件
        exportButton.addActionListener(e -> {
            // 判断是否设置了班级
            if (currentClass == null) {
                JOptionPane.showMessageDialog(classListFrame, "请先设置班级！");
                return;
            }

            // 定义导出文件的路径（例如桌面）
            String fileName = currentClass.getName() + "_成绩.csv"; // 使用当前班级的名字
            File file = new File(System.getProperty("user.home") + "/Desktop/" + fileName); // 将文件保存在桌面

            try (PrintWriter writer = new PrintWriter(file)) {
                // 写入表头
                writer.println("学号,姓名,成绩");

                // 获取当前班级的学生列表
                List<Student> classStudents = studentList.stream()
                        .filter(student -> student.getGroup().getClassId().equals(currentClass.getId()))
                        .collect(Collectors.toList());

                // 写入每个学生的信息
                for (Student student : classStudents) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(student.getId()).append(",");
                    sb.append(student.getName()).append(",");

                    if (student.getScore() != null) {
                        sb.append(student.getScore());  // 如果有成绩，写入成绩
                    } else {
                        sb.append("无成绩");  // 如果没有成绩，写入"无成绩"
                    }

                    writer.println(sb.toString());
                }

                // 提示导出成功
                JOptionPane.showMessageDialog(classListFrame, "成绩导出成功！文件已保存至桌面：" + fileName);
            } catch (FileNotFoundException ex) {
                // 捕获文件未找到异常
                JOptionPane.showMessageDialog(classListFrame, "无法创建成绩导出文件：" + ex.getMessage());
            }
        });

        // 删除按钮事件
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int confirm = JOptionPane.showConfirmDialog(classListFrame, "确认要删除该班级吗？", "删除班级", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    CourseClass classToRemove = classList.get(selectedRow);
                    // 删除班级
                    classList.remove(selectedRow);

                    // 删除属于该班级的小组和学生
                    groupList.removeIf(group -> group.getClassId().equals(classToRemove.getId()));
                    studentList.removeIf(student -> student.getGroup().getClassId().equals(classToRemove.getId()));

                    // 清空当前班级
                    if (currentClass != null && currentClass.getId().equals(classToRemove.getId())) {
                        currentClass = null;
                        MenuFrame.updateCurrentClassLabel("请选择班级");
                    }

                    JOptionPane.showMessageDialog(classListFrame, "班级及其相关的小组和学生已删除");

                    // 更新表格数据
                    String[][] newData = new String[classList.size()][2];
                    for (int i = 0; i < classList.size(); i++) {
                        CourseClass cls = classList.get(i);
                        newData[i][0] = cls.getId();
                        newData[i][1] = cls.getName();
                    }
                    table.setModel(new javax.swing.table.DefaultTableModel(newData, columnNames));
                }
            } else {
                JOptionPane.showMessageDialog(classListFrame, "请先选择一个班级");
            }
        });

        // 返回按钮事件
        backButton.addActionListener(e -> {
            classListFrame.dispose();
            MenuFrame.updateCurrentClassLabel(currentClass != null ? currentClass.getName() : "请选择班级");
            MenuFrame.showMenuFrame();
        });

        // 添加按钮到面板
        buttonPanel.add(queryButton);
        buttonPanel.add(setClassButton);
        buttonPanel.add(exportButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(backButton);

        // 添加按钮面板到底部
        classListFrame.add(buttonPanel, BorderLayout.SOUTH);

        // 显示窗口
        classListFrame.setVisible(true);
    }


    // 随机小组管理
    public static void showRandomGroupFrame() {
        JFrame randomGroupFrame = new JFrame("随机小组");
        randomGroupFrame.setSize(450, 650);
        randomGroupFrame.setLocationRelativeTo(null);
        randomGroupFrame.setLayout(new BorderLayout());

        // 创建顶部标签
        JLabel titleLabel = new JLabel("随机小组", JLabel.CENTER);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 18));
        randomGroupFrame.add(titleLabel, BorderLayout.NORTH);

        // 创建中央面板，使用 GridBagLayout 来调整组件对齐
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);  // 添加间距
        gbc.fill = GridBagConstraints.HORIZONTAL;  // 让组件填充可用空间

        // 小组输入框
        JTextField groupField = new JTextField();
        groupField.setEditable(false);
        groupField.setPreferredSize(new Dimension(200, 30));  // 调整宽度
        gbc.gridx = 0;
        gbc.gridy = 0;
        centerPanel.add(new JLabel("小组："), gbc);
        gbc.gridx = 1;
        centerPanel.add(groupField, gbc);

        // 随机按钮
        JButton groupRandomButton = new JButton("随机");
        gbc.gridx = 1;
        gbc.gridy = 1;
        centerPanel.add(groupRandomButton, gbc);

        // 姓名输入框
        JTextField nameField = new JTextField();
        nameField.setEditable(false);
        nameField.setPreferredSize(new Dimension(200, 30));  // 调整宽度
        gbc.gridx = 0;
        gbc.gridy = 2;
        centerPanel.add(new JLabel("姓名："), gbc);
        gbc.gridx = 1;
        centerPanel.add(nameField, gbc);

        // 照片占位符
        ImageIcon icon = new ImageIcon(MenuFrame.class.getResource("/resources/images/bg2.png"));
        JLabel photoLabel = new JLabel(icon, JLabel.CENTER);
        photoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;  // 照片占据两列
        centerPanel.add(new JLabel("照片："), gbc);
        centerPanel.add(photoLabel, gbc);

        // 分数输入框
        JTextField scoreField = new JTextField();
        scoreField.setPreferredSize(new Dimension(200, 30));  // 调整宽度
        gbc.gridx = 0;
        gbc.gridy = 4;
        centerPanel.add(new JLabel("分数："), gbc);
        gbc.gridx = 1;
        centerPanel.add(scoreField, gbc);

        randomGroupFrame.add(centerPanel, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 20));  // 设置按钮间距

        JButton studentRandomButton = new JButton("随机");
        JButton evaluateButton = new JButton("评分");
        JButton leaveButton = new JButton("请假");
        JButton absentButton = new JButton("缺勤");
        JButton backButton = new JButton("返回");

        buttonPanel.add(studentRandomButton);
        buttonPanel.add(evaluateButton);
        buttonPanel.add(leaveButton);
        buttonPanel.add(absentButton);
        buttonPanel.add(backButton);

        randomGroupFrame.add(buttonPanel, BorderLayout.SOUTH);

        // 小组随机按钮逻辑
        Timer groupTimer = new Timer(50, null);
        groupRandomButton.addActionListener(e -> {
            if (groupRandomButton.getText().equals("随机")) {
                groupRandomButton.setText("停");
                groupTimer.addActionListener(ev -> {
                    if (!groupList.isEmpty()) {
                        int index = new Random().nextInt(groupList.size());
                        groupField.setText(groupList.get(index).getName());
                    }
                });
                groupTimer.start();
            } else {
                groupRandomButton.setText("随机");
                groupTimer.stop();
            }
        });

        // 学生随机按钮逻辑
        Timer studentTimer = new Timer(50, null);
        studentRandomButton.addActionListener(e -> {
            if (groupField.getText().isEmpty()) {
                JOptionPane.showMessageDialog(randomGroupFrame, "请先选择小组");
                return;
            }

            Group selectedGroup = groupList.stream()
                    .filter(group -> group.getName().equals(groupField.getText()))
                    .findFirst().orElse(null);

            if (selectedGroup != null) {
                List<Student> groupStudents = studentList.stream()
                        .filter(student -> student.getGroup().equals(selectedGroup))
                        .collect(Collectors.toList());

                if (studentRandomButton.getText().equals("随机")) {
                    studentRandomButton.setText("停");
                    studentTimer.addActionListener(ev -> {
                        if (!groupStudents.isEmpty()) {
                            int index = new Random().nextInt(groupStudents.size());
                            nameField.setText(groupStudents.get(index).getName());
                        }
                    });
                    studentTimer.start();
                } else {
                    studentRandomButton.setText("随机");
                    studentTimer.stop();
                }
            }
        });

        // 评分按钮逻辑
        evaluateButton.addActionListener(e -> {
            String score = scoreField.getText().trim();
            if (!score.isEmpty()) {
                JOptionPane.showMessageDialog(randomGroupFrame, "评分成功");
            } else {
                JOptionPane.showMessageDialog(randomGroupFrame, "请输入分数");
            }
        });

        // 请假按钮逻辑
        leaveButton.addActionListener(e -> JOptionPane.showMessageDialog(randomGroupFrame, "请假成功"));

        // 缺勤按钮逻辑
        absentButton.addActionListener(e -> JOptionPane.showMessageDialog(randomGroupFrame, "缺勤登记成功"));

        // 返回按钮逻辑
        backButton.addActionListener(e -> {
            randomGroupFrame.dispose();
            MenuFrame.updateCurrentClassLabel(currentClass != null ? currentClass.getName() : "请选择班级");
            MenuFrame.showMenuFrame();
        });

        randomGroupFrame.setVisible(true);
    }



    // 随机学生管理
    public static void showRandomStudentFrame() {
        JFrame randomStudentFrame = new JFrame("随机学生");
        randomStudentFrame.setSize(450, 500);
        randomStudentFrame.setLocationRelativeTo(null);
        randomStudentFrame.setLayout(new BorderLayout());

        // 创建顶部标签
        JLabel titleLabel = new JLabel("随机学生", JLabel.CENTER);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 18));
        randomStudentFrame.add(titleLabel, BorderLayout.NORTH);

        // 创建中央面板，使用 GridBagLayout 来调整组件对齐
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);  // 添加间距
        gbc.fill = GridBagConstraints.HORIZONTAL;  // 让组件填充可用空间

        // 姓名输入框
        JTextField nameField = new JTextField();
        nameField.setEditable(false);
        nameField.setPreferredSize(new Dimension(200, 30));  // 调整宽度
        gbc.gridx = 0;
        gbc.gridy = 0;
        centerPanel.add(new JLabel("姓名："), gbc);
        gbc.gridx = 1;
        centerPanel.add(nameField, gbc);

        // 照片占位符
        ImageIcon icon = new ImageIcon(MenuFrame.class.getResource("/resources/images/bg2.png"));
        JLabel photoLabel = new JLabel(icon, JLabel.CENTER);
        photoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;  // 照片占据两列
        centerPanel.add(new JLabel("照片："), gbc);
        centerPanel.add(photoLabel, gbc);

        // 分数输入框
        JTextField scoreField = new JTextField();
        scoreField.setPreferredSize(new Dimension(200, 30));  // 调整宽度
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        centerPanel.add(new JLabel("分数："), gbc);
        gbc.gridx = 1;
        centerPanel.add(scoreField, gbc);

        randomStudentFrame.add(centerPanel, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 20));  // 设置按钮间距

        JButton randomButton = new JButton("随机");
        JButton evaluateButton = new JButton("评分");
        JButton leaveButton = new JButton("请假");
        JButton absentButton = new JButton("缺勤");
        JButton backButton = new JButton("返回");

        buttonPanel.add(randomButton);
        buttonPanel.add(evaluateButton);
        buttonPanel.add(leaveButton);
        buttonPanel.add(absentButton);
        buttonPanel.add(backButton);

        randomStudentFrame.add(buttonPanel, BorderLayout.SOUTH);

        // 随机按钮逻辑
        List<Student> currentClassStudents = studentList.stream()
                .filter(student -> student.getGroup().getClassId().equals(currentClass.getId()))
                .collect(Collectors.toList());

        Timer timer = new Timer(50, null);
        randomButton.addActionListener(e -> {
            if (randomButton.getText().equals("随机")) {
                randomButton.setText("停");
                timer.addActionListener(ev -> {
                    if (!currentClassStudents.isEmpty()) {
                        int index = new Random().nextInt(currentClassStudents.size());
                        nameField.setText(currentClassStudents.get(index).getName());
                    }
                });
                timer.start();
            } else {
                randomButton.setText("随机");
                timer.stop();
            }
        });

        // 评分按钮逻辑
        evaluateButton.addActionListener(e -> {
            String score = scoreField.getText().trim();
            if (!score.isEmpty()) {
                JOptionPane.showMessageDialog(randomStudentFrame, "评分成功");
            } else {
                JOptionPane.showMessageDialog(randomStudentFrame, "请输入分数");
            }
        });

        // 请假按钮逻辑
        leaveButton.addActionListener(e -> JOptionPane.showMessageDialog(randomStudentFrame, "请假成功"));

        // 缺勤按钮逻辑
        absentButton.addActionListener(e -> JOptionPane.showMessageDialog(randomStudentFrame, "缺勤登记成功"));

        // 返回按钮逻辑
        backButton.addActionListener(e -> {
            randomStudentFrame.dispose();
            MenuFrame.updateCurrentClassLabel(currentClass != null ? currentClass.getName() : "请选择班级");
            MenuFrame.showMenuFrame();
        });

        randomStudentFrame.setVisible(true);
    }


    public static void exportClassScores() {
        if (currentClass == null) {
            JOptionPane.showMessageDialog(null, "请先设置班级！");
            return;
        }

        // 定义文件输出路径（可以选择用户的桌面或者其他位置）
        String fileName = currentClass.getName() + "_成绩.csv";
        File file = new File(System.getProperty("user.home") + "/Desktop/" + fileName);

        try (PrintWriter writer = new PrintWriter(file)) {
            // CSV文件标题
            writer.println("学号,姓名,成绩");

            // 获取当前班级的所有学生
            List<Student> classStudents = studentList.stream()
                    .filter(student -> student.getGroup().getClassId().equals(currentClass.getId()))
                    .collect(Collectors.toList());

            // 写入每个学生的信息
            for (Student student : classStudents) {
                StringBuilder sb = new StringBuilder();
                sb.append(student.getId()).append(",");
                sb.append(student.getName()).append(",");

                if (student.getScore() != null) {
                    sb.append(student.getScore());
                } else {
                    sb.append("无成绩");
                }

                writer.println(sb.toString());
            }

            JOptionPane.showMessageDialog(null, "成绩导出成功！文件已保存至桌面：" + fileName);
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "无法创建成绩导出文件：" + e.getMessage());
        }
    }


}
